using System;
using System.Collections.Generic;
using Servlets.Api;
using Servlets.Server;

namespace Servlets
{
	class Session : ISession
	{
		internal static int SessionLengthInDays {get;set;}
					
		private static Serializer _serializer = null;
		private static Serializer Serializer{
			get {
				return _serializer ?? (_serializer = new Serializer());
			}
		}
		
		private IResponse response;
		public string Id{get;set;}
				
		public IEnumerable<string> Keys {
			get {
				return null;
			}
		}
		
		//TODO when Mono supports Dynamic, make it so that the keys can be accessed as properties
		public object this [string key]{
			get {				
				return Serializer.Deserialize(Id, key); 
			}
			set {
				if(response != null) {
					/*
					 * if this is the first time the session object is used,
					 * create a new cookie in the response. But we only want
					 * to add the cookie once, so just set the response to
					 * null after we set the session cookie.
					*/
					response.SetCookie(new Cookie(Http.HttpRequest.SESSION_COOKIE, this.Id, DateTime.Now.AddDays(SessionLengthInDays)));
					response = null;
				}
				Serializer.Serialize(Id, key, value); 
			}
		}
		
		public Session(IResponse response) {
			this.Id = Guid.NewGuid().ToString();
			this.response = response;
		}
		
		public Session(string id) {
			this.Id = id;
		}
	}
}